<template>
  <div class="user-manage">
    <div class="header">
      <h2>用户管理</h2>
      <button @click="showAddDialog = true">添加用户</button>
    </div>

    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>账号</th>
          <th>手机号</th>
          <th>性别</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in userList" :key="user.CusId">
          <td>{{ user.CusId }}</td>
          <td>{{ user.CusName }}</td>
          <td>{{ user.CusAccount }}</td>
          <td>{{ user.CusPhone }}</td>
          <td>{{ user.CusSex }}</td>
          <td>{{ user.CreateTime }}</td>
          <td>
            <button class="edit-btn" @click="handleEdit(user)">编辑</button>
            <button class="delete-btn" @click="handleDelete(user.CusId)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 添加用户对话框 -->
    <div v-if="showAddDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>添加用户</h3>
        <form @submit.prevent="handleAdd">
          <div class="form-item">
            <label>用户名：</label>
            <input type="text" v-model="formData.CusName" required>
          </div>
          <div class="form-item">
            <label>手机号：</label>
            <input type="tel" v-model="formData.CusPhone" required>
          </div>
          <div class="form-item">
            <label>性别：</label>
            <select v-model="formData.CusSex" required>
              <option value="男">男</option>
              <option value="女">女</option>
            </select>
          </div>
          <div class="form-item">
            <label>账号：</label>
            <input type="text" v-model="formData.CusAccount" required>
          </div>
          <div class="form-item">
            <label>密码：</label>
            <input type="password" v-model="formData.CusPassword" required>
          </div>
          <div class="dialog-actions">
            <button type="submit">确定</button>
            <button type="button" @click="showAddDialog = false">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 编辑用户对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>编辑用户</h3>
        <form @submit.prevent="handleUpdate">
          <div class="form-item">
            <label>用户名：</label>
            <input type="text" v-model="formData.CusName" required>
          </div>
          <div class="form-item">
            <label>手机号：</label>
            <input type="tel" v-model="formData.CusPhone" required>
          </div>
          <div class="form-item">
            <label>性别：</label>
            <select v-model="formData.CusSex" required>
              <option value="男">男</option>
              <option value="女">女</option>
            </select>
          </div>
          <div class="dialog-actions">
            <button type="submit">确定</button>
            <button type="button" @click="showEditDialog = false">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'

interface User {
  CusId: number
  CusName: string
  CusAccount: string
  CusPhone: string
  CusSex: string
  CreateTime: string
  CusPassword?: string
}

const userList = ref<User[]>([])
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const formData = ref({
  CusId: '',
  CusName: '',
  CusPhone: '',
  CusSex: '男',
  CusAccount: '',
  CusPassword: ''
})

// 初始化表单数据
const initFormData = () => {
  formData.value = {
    CusId: '',
    CusName: '',
    CusPhone: '',
    CusSex: '男',
    CusAccount: '',
    CusPassword: ''
  }
}

// 监听对话框状态
watch(showAddDialog, (newVal) => {
  if (newVal) {
    // 打开添加对话框时初始化表单
    initFormData()
  }
})

watch(showEditDialog, (newVal) => {
  if (!newVal) {
    // 关闭编辑对话框时初始化表单
    initFormData()
  }
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    console.log('用户列表响应:', res)
    if (res.code === 200) {
      userList.value = res.data
    } else {
      throw new Error(res.message || '获取列表失败')
    }
  } catch (error: any) {
    console.error('获取列表错误:', error)
    alert(error.message)
  }
}

// 添加用户
const handleAdd = async () => {
  try {
    const res = await addUser(formData.value)
    if (res.code === 200) {
      showAddDialog.value = false
      initFormData()
      await fetchUserList()
      alert('添加成功')
    } else {
      throw new Error(res.message || '添加失败')
    }
  } catch (error: any) {
    alert(error.message)
  }
}

// 编辑用户
const handleEdit = (user: User) => {
  formData.value = { ...user, CusPassword: '' }
  showEditDialog.value = true
}

// 更新用户
const handleUpdate = async () => {
  try {
    const res = await updateUser(formData.value)
    if (res.code === 200) {
      showEditDialog.value = false
      initFormData()
      await fetchUserList()
      alert('更新成功')
    } else {
      throw new Error(res.message || '更新失败')
    }
  } catch (error: any) {
    alert(error.message)
  }
}

// 删除用户
const handleDelete = async (CusId: number) => {
  if (!confirm('确定要删除该用户吗？')) return
  try {
    await deleteUser(String(CusId))
    // 直接从本地列表中移除该用户，不再重新获取列表
    userList.value = userList.value.filter(user => user.CusId !== CusId)
    alert('删除成功')
  } catch (error: any) {
    console.error('删除错误:', error)
    alert(error.message)
    // 如果删除失败，重新获取列表以保持数据同步
    await fetchUserList()
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manage {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
  color: #333;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #fafafa;
  font-weight: 500;
  color: #666;
}

.edit-btn, .delete-btn {
  padding: 4px 8px;
  margin-right: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #409eff;
  color: white;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  color: #666;
}

.form-item input,
.form-item select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background-color: #409eff;
  color: white;
}

button[type="button"] {
  background-color: #909399;
}

button:hover {
  opacity: 0.9;
}
</style> 